package com.rainwood.water_authority.util;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.widget.FrameLayout;

/**
 * @author sxs
 * @date :2020/9/28
 * @desc: 解决软键盘挡住输入框问题
 */
public final class SoftHideKeyBoardUtils {

    public static void assistActivity(Activity activity) {
        new SoftHideKeyBoardUtils(activity);
    }

    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams; //为适应华为小米等手机键盘上方出现黑条或不适配
    private int contentHeight;//获取setContentView本来view的高度
    private boolean isFirst = true;//只用获取一次
    private int statusBarHeight;//状态栏高度

    private SoftHideKeyBoardUtils(Activity activity) {
        //获得Activity的最外层布局控件
        FrameLayout content = activity.findViewById(android.R.id.content);
        if (content.getChildCount() == 0) {
            return;
        }
        mChildOfContent = content.getChildAt(0);
        //布局设置View树监听，当布局有变化，如键盘弹出或收起时，都会回调此监听
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            if (isFirst) {
                contentHeight = mChildOfContent.getHeight();//兼容华为等机型
                isFirst = false;
            }
            //当前布局发生变化时，对布局进行重绘
            possiblyResizeChildOfContent();
        });
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
    }

    // 获取界面可用高度，如果软键盘弹起后，Activity的可用高度需要减去键盘高度
    private void possiblyResizeChildOfContent() {
        //获取当前界面可用高度，键盘弹起后，当前界面可用布局会减少键盘的高度
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            //获取布局在当前界面显示的高度
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            //布局的高度-当前可用高度
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            //高度差大于屏幕1/4时，说明键盘弹出
            if (heightDifference > (usableHeightSansKeyboard / 4)) {
                //键盘弹出了，布局高度应当减去键盘高度
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    frameLayoutParams.height = usableHeightSansKeyboard - heightDifference + statusBarHeight;
                } else {
                    frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
                }
            } else {
                frameLayoutParams.height = contentHeight;
            }
            //重绘Activity布局
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);// 全屏模式下：直接返回r.bottom，r.top其实是状态栏的高度
    }
}
